package cn.jfast.framework.jdbc.orm;

import java.sql.SQLException;

/**
 * Sql执行器
 */
public abstract class Executor extends Parser{

    /**
     * Sql执行
     * @return
     * @throws SQLException
     * @throws IllegalAccessException
     * @throws NoSuchFieldException
     * @throws InstantiationException
     */
    public Object execute() throws SQLException, IllegalAccessException, NoSuchFieldException, InstantiationException {
        Object reObj = null;
        conn.setCatalog(dao.getClass().getSimpleName()+"."+method.getName());
        ps = conn.prepareStatement(parseSql());
        fillPreparedStatement();
        if(returnType == void.class)
            ps.executeUpdate();
        else if(returnType == Boolean.class || returnType == Boolean.TYPE)
            reObj = ps.execute();
        else if(returnType == Integer.class || returnType == Integer.TYPE)
            reObj = ps.executeUpdate();
        if(conn.getAutoCommit() == true && !conn.isClosed())
            conn.close();
        return reObj;
    }

    /**
     * 对PreparedStatement赋值
     */
    public void fillPreparedStatement() throws SQLException {
       for(int i = 1; i<=sqlFields.size(); i++){
           ps.setObject(i,paramMaps.get(sqlFields.get(i-1).toLowerCase()));
       }
    }
}
